package org.osomit.sacct.session.token.impl;

import org.osomit.sacct.session.token.iface.RandomStringGenerator;

import java.security.SecureRandom;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jul 2, 2009
 */
public class RandomStringGeneratorImpl implements RandomStringGenerator {

    // The array of printable characters to be used in our random string.
    private static final char[] PRINTABLE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            .toCharArray();

    private SecureRandom randomizer = new SecureRandom();

    public synchronized String getNewString(int length) {
        final byte[] random = new byte[length];

        this.randomizer.nextBytes(random);

        return convertBytesToString(random);
    }

    private String convertBytesToString(final byte[] random) {
        final char[] output = new char[random.length];
        for (int i = 0; i < random.length; i++) {
            final int index = Math.abs(random[i] % PRINTABLE_CHARACTERS.length);
            output[i] = PRINTABLE_CHARACTERS[index];
        }

        return new String(output);
    }
}
